<?php

namespace app\backend\service;
use app\backend\validate\ContentValidate;
use app\common\model\CategoryModel;
use app\common\model\ContentBodyModel;
use app\common\model\ContentModel;
use app\common\model\SourceModel;
use app\common\RootService;

class ContentService extends RootService
{
    /**
     * 内容标签
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function contentLabel()
    {
        return ['type' => $this->getType(), 'currType' => ContentModel::$typeLabel[$this->getType()], 'color' => ContentModel::$color,
            'stateLabel' => ContentModel::$stateLabel, 'adminNames' => AdminService::adminNames(),
            'category' => $this->categoryList(),
            'source' => SourceModel::field(['id value', 'name'])->select()->toArray()];
    }

    /**
     * 文章内容列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function lists(array $params)
    {
        // 置换标签
        $contentLabel = $this->contentLabel();
        // 栏目名称
        $catNames = array_column($contentLabel['category'], null, 'value');
        // 来源名称
        $sourceNames = array_column($contentLabel['source'], null, 'value');
        // 数据源
        $contentList = $this->contentModel($params)->order(['id' => 'desc'])->paginate($params['limit'] ?? 10)->toArray();
        // 数据处理
        array_walk($contentList['data'], function (&$row) use ($contentLabel, $catNames, $sourceNames) {
            $row['color'] = $contentLabel['color'][$row['state']] ?? '';
            $row['categoryName'] = $catNames[$row['cat_id']]['name'] ?? '--';
            $row['sourceName'] = $sourceNames[$row['source_id']]['name'] ?? '--';
            $row['stateLabel'] = $contentLabel['stateLabel'][$row['state']] ?? '--';
            $row['auditName'] = $contentLabel[$row['admin_id']]['real_name'] ?? '--';
        });
        return $contentList;
    }

    /**
     * 新增操作
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function add(array $params)
    {
        $contentModel = new ContentModel();
        $tipMsg = "【{$params['title']}】添加";
        // 参数校验
        $this->validate(new ContentValidate(), 'add');
        try {
            $contentModel->startTrans();
            $contentInfo = $contentModel->create($this->formData($params));
            // 添加详情内容
            ContentBodyModel::create(['content_id' => $contentInfo['id'], 'content' => $params['content']]);
            $contentModel->commit();
        } catch (\Exception $e) {
            $contentModel->rollback();
            // 添加失败
            $this->errorException($tipMsg . '失败' . $e->getMessage());
        }
        // 添加成功
        return ['msg' => $tipMsg . '成功', 'preload' => true];
    }

    /**
     * 编辑操作
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function edit(array $params)
    {
        $contentModel = new ContentModel();
        $tipMsg = "【{$params['title']}】修改";
        // 参数校验
        $this->validate(new ContentValidate(), 'edit');
        try {
            $contentModel->startTrans();
            ContentModel::update($this->formData($params));
            // 更新内容
            ContentBodyModel::update(['content_id' => $params['id'], 'content' => $params['content']]);
            $contentModel->commit();
        } catch (\Exception $e) {
            // 编辑失败
            $contentModel->rollback();
            $this->errorException($tipMsg . '失败' . $e->getMessage());
        }
        // 编辑成功
        return ['msg' => $tipMsg . '成功', 'preload' => true];
    }

    /**
     * 详情
     * @param int $contentId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $contentId)
    {
        return ContentModel::alias('c')->join(['sys_content_body' => 'cb'], 'c.id = cb.content_id', 'left')
            ->where(['id' => $contentId])->field(['*', 'cb.content contentHtml'])->find()->toArray();
    }

    /**
     * 删除文章
     * @param int $contentId
     * @return array
     * @throws \app\common\RootException
     */
    public function del(int $contentId)
    {
        // 删除失败
        $contentModel = new ContentModel();
        try {
            $contentModel->startTrans();
            ContentModel::where(['id' => $contentId])->delete(); // 删除文章
            ContentBodyModel::where(['content_id' => $contentId])->delete(); // 删除内容
            $contentModel->commit();
        } catch (\Exception $e) {
            // 删除失败
            $contentModel->rollback();
            $this->errorException('删除失败' . $e->getMessage());
        }
        return ['msg' => '删除成功', 'preload' => true];
    }

    /**
     * 数据处理
     * @param array $params
     * @return array
     */
    protected function formData(array $params)
    {
        $formData = ['cat_id' => $params['catId'], 'state' => $params['state'], 'type' => $this->getType(),
            'title' => $params['title'], 'sort' => $params['sort']];
        // 添加 OR 编辑
        empty($params['id']) ? $formData['admin_id'] = adminInfo('id') : $formData['id'] = $params['id'];
        return $formData;
    }

    /**
     * 文章类型
     * @return mixed
     */
    protected function getType()
    {
        return cache('contentType' . adminInfo('id')) ?: 0;
    }

    /**
     * 分类列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function categoryList()
    {
        return CategoryModel::field(['id value', 'title name'])->where(['type' => 0])->order(['rank' => 'asc'])
            ->select()->toArray();
    }

    /**
     * 内容模型
     * @param array $params
     * @return ContentModel
     */
    protected function contentModel(array $params)
    {
        $where = [['type', '=', $this->getType()]];
        // 标题筛选
        empty($params['title']) || $where[] = ['title', 'like', $params['title'] . '%'];
        // 日期筛选
        empty($params['createTime']) || $where[] = ['create_time', 'between', betweenDate($params['createTime'])];
        // 状态筛选
        condition($params['state'] ?? '') && $where[] = ['state', 'in', explode(',', $params['state'])];
        // 栏目筛选
        condition($params['catId'] ?? '') && $where[] = ['cat_id', 'in', explode(',', $params['catId'])];
        // 来源筛选
        condition($params['sourceId'] ?? '') && $where[] = ['source_id', 'in', explode(',', $params['sourceId'])];
        // 筛选结果
        return ContentModel::where($where);
    }
}